package com.person.leetcode.editor.cn;

import java.util.List;

/**
 * 19.删除链表的倒数第 N 个结点
 * 2022-06-08 11:36:19
 **/
public class Sequence_0019_RemoveNthNodeFromEndOfList {
    public static void main(String[] args) {
        Solution solution = new Sequence_0019_RemoveNthNodeFromEndOfList().new Solution();
    }
    //leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     * int val;
     * ListNode next;
     * ListNode() {}
     * ListNode(int val) { this.val = val; }
     * ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode removeNthFromEnd(ListNode h, int n) {
            ListNode e = h;//end
            ListNode t = h;//taget
            ListNode pref = h;//断点
            int len = 0;
            while (e != null) {
                if (len > n-1) {
                    pref = t;
                    t = t.next;
                }
                e = e.next;//最后一个
                len++;//记录长度
            }
            if (pref == t){
                return h.next;
            }else
            if (pref == null || t == null){
                return h;
            }else{
                pref.next = t.next;
                return h;
            }

        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}